#!/bin/bash

scriptPath=$(dirname $0);
echo "event spread analysis"

if [ -f connectivityEvents.sqlite ]
then rm connectivityEvents.sqlite
fi

cat $scriptPath/connectivityEvents-sql.begin > connectivityEvents.sql
expNum=1



# --- scenario (.trc)
if [ -f *.trc ];
then traceFile=$(ls -d *.trc)
	echo $traceFile
   	awk -f $scriptPath/trc2sql.awk $traceFile >> connectivityEvents.sql
fi


# --- go through all experiments
for logPath in $(ls -d *)
do 
	if [[ -d $logPath  &&  ! -f $logPath/trace.sqlite ]]
	then  
		cd $logPath
		sh $scriptPath/analysis.sh
		sh $scriptPath/trace.sh
		cd ..
	fi

	# --- end-to-end delay (from tmp-delay-net)
	if [[ -d $logPath  &&  -f $logPath/tmp-delay-net ]]
	then
		awk -f $scriptPath/delay-e2e.awk -v expNum="$expNum" $logPath/tmp-delay-net >> connectivityEvents.sql
	fi


	# --- haggle log (from trace.sqlite)
	if [[ -d $logPath  &&  -f $logPath/trace.sqlite ]]
	then
		sqlite3 -batch -separator ' ' $logPath/trace.sqlite "SELECT round(time*1000) as logtime, device as nodeA, interfaceId as nodeB, lower(substr(eventName,31,4)) as action  from events WHERE eventName='EVENT_TYPE_NEIGHBOR_INTERFACE_UP' OR eventName='EVENT_TYPE_NEIGHBOR_INTERFACE_DOWN' ORDER BY nodeA, nodeB, time;" | awk -f $scriptPath/connectivityEvents2sql.awk -v expNum="$expNum" >> connectivityEvents.sql
	fi

	# --- testbed log
	if [ -d $logPath ] && [ -f $logPath/*.log ];
	then traceFile=$(ls -d $logPath/*.log)
		echo $traceFile
		cat $traceFile | awk -f $scriptPath/eventSpread-log.awk -v expNum="$expNum" >> connectivityEvents.sql		
		
	   	expNum=$[$expNum+1]
	fi
done

cat $scriptPath/connectivityEvents-sql.end >> connectivityEvents.sql

echo .. create database
sqlite3 -batch -separator ' ' connectivityEvents.sqlite < connectivityEvents.sql

# select substr(dataobjectId,0,4), substr(nodeId,0,2), count(*), avg(delay), max(delay)-min(delay), avg(hop), max(hop)-min(hop) from delays group by dataobjectId, nodeId;

